import { makeAutoObservable } from "mobx";
import React from "react";
import * as apis from '@shared/apis';

export class PageController {

    static Context = React.createContext<PageController>(undefined as any);

    /** 当前页码 */
    page = 1;

    /** 每页数量 */
    pageSize = 10;

    /** 搜索关键词 */
    keyword = '';

    /** 总数量 */
    total = 1;

    /** 是否加载中 */
    loading = 0;

    /** 产品列表 */
    data: apis.products.IProduct[] = [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}] as any;

    /** 统计数据 */
    statistics = {
        totalProducts: 0,
        inStockProducts: 0,
        lowStockProducts: 0,
        totalValue: 0
    };

    constructor() {
        makeAutoObservable(this);
    }

    /** 查询指定页码的数据 */
    query = async () => {
        if (this.loading > 0 || this.data.length >= this.total) return;
        try {
            this.loading++;
            const data = await apis.products.list.post({
                page: this.page,
                pageSize: this.pageSize,
                keyword: this.keyword,
            });
            this.data = data.items;
            this.total = data.pagination.total;
            this.updateStatistics();
        } catch (error) {
            console.log(error);
        }
        finally {
            this.loading--;
        }
    }

    /** 更新统计数据 */
    updateStatistics = () => {
        this.statistics.totalProducts = this.data.length;
        this.statistics.inStockProducts = this.data.filter(item => item.stockQuantity > 0).length;
        this.statistics.lowStockProducts = this.data.filter(item => item.stockQuantity <= item.warningQuantity).length;
        this.statistics.totalValue = this.data.reduce((sum, item) => sum + (item.retailPrice * item.stockQuantity), 0);
    }

    /** 设置 搜索关键词 */
    setKeyword = (keyword: string) => {
        this.keyword = keyword;
        this.page = 1;
        this.total = 1;
        this.data = [];
        this.query();
    }
} 